import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Modal, Button, Splitter,  App } from "antd";
import styles from "./styles.module.scss";
import Category from "./Category";
import ToolBar from "./ToolBar";
import FileList from "./FileList";
import DPlayer from "dplayer";
import DiskInfo from "./DiskInfo";
import { FileProvider } from "./Context";
import { queueCallFunc } from "elmer-common/lib/BaseModule/QueueCallFun";
import { useService } from "@/lib/Service";

interface IFileManageProps {
    mulitpleSelected?: boolean;
    filterType?: "image"|"video"| "audio" | "pdf";
    defaultSelected?: string[];
    onConfirm?: (fileList: any[], sourceList: any[]) => void;
    onCancel?: () => void;
    validate?: (file: File) => boolean;
}

const FileManage = (props: IFileManageProps) => {

    const player = useRef<DPlayer>();
    const playerRef = useRef<HTMLDivElement>(null);
    const [ playerStyle, setPlayerStyle ] = useState({ display: "none"});
    const [ selectedList, setSelectedList ] = useState(props.defaultSelected || []);
    const [ selectedSourceList, setSelectedSourceList] = useState<any[]>([]);
    const [ hasChanged, setHasChanged ] = useState(false);
    const service = useService();
    const app = App.useApp();
    const message = App.useApp().message;
    const onPlayVideo = useCallback((url: string) => {
        setPlayerStyle({ display: "block"});
        if(player.current) {
            (player.current as any).switchVideo({
                url
            });
            player.current.play();
        }
    }, [player]);
    const showPlayerBack = useMemo(() => {
        return playerStyle.display === "block";
    }, [playerStyle]);
    const confirmProps = useMemo(() => selectedList.length > 0 && hasChanged ? {} : { disabled: true }, [ selectedList, hasChanged ]);
    
    const fileValidate = useCallback((fileList: string[]) => {
        return queueCallFunc(fileList, (fileId) => {
            return new Promise((resolve, reject) => {
                console.log("fileId: ", fileId);
                service.send({
                    endPoint: "files.getFileInfo",
                    "variables": {
                        id: fileId.id
                    }
                }).then((resp: any) => {
                    if(typeof props.validate === "function" && !props.validate(({
                        "name": resp.data.originalName,
                        "type": resp.data.fileType,
                        "size": resp.data.size
                    }) as any)) {
                        const fileData = selectedSourceList.find((v) => v.id === fileId.id);
                        reject({
                            name: fileData.name,
                            message: "选择文件大小超出限制或不允许的文件类型。" + fileData.name
                        });
                    } else {
                        resolve(resp.data);
                    }
                }).catch((err) => {
                    const fileData = selectedSourceList.find((v) => v.id === fileId.id);
                    reject({
                        name: fileData.originalName,
                        message: err.message || "获取文件信息失败",
                    });
                });
            });
        }, {
            paramConvert: (param: any, index) => {
                return {
                    params: param as any,
                    id: param || index.toString()
                } as any;
            },
            throwException: true
        });
    }, [selectedSourceList]);
    
    useEffect(() => {
        if(playerRef.current) {
            player.current = new DPlayer({
                container: playerRef.current,
                video: {
                    url: "https://cdn.jsdelivr.net/gh/xiaoyu-zhang/cdn@main/video/%E5%A4%A9%E5%A4%A9%E5%A4%A9%E5%A4%A9%E5%A4%A9%E5%A4%A9%E5%A4%A"
                }
            });
        }
    }, [playerRef]);



    return (
        <FileProvider selectedList={selectedList} filterType={props.filterType}>
            <Modal
                title="文件管理"
                open
                width={900}
                onClose={() => typeof props.onCancel === "function" && props.onCancel()}
                footer={<>
                    <DiskInfo />
                    { showPlayerBack && <Button type="primary" onClick={()=>{
                        setPlayerStyle({ display: "none"});
                        player.current?.pause();
                    }}>返回</Button>}
                    { !showPlayerBack && <Button {...confirmProps} type="primary" onClick={() => {
                        fileValidate(selectedList).then((resp) => {
                            console.log(resp);
                            typeof props.onConfirm === "function" && props.onConfirm(selectedList, selectedSourceList);
                        }).catch((err) => {
                            console.log(err);
                            app.modal.error({
                                "title": "不允许的文件",
                                "content": err.exception.message || "操作失败，未知错误",
                                "type": "error"
                            });

                        });
                    }}>确定</Button>}
                    <Button onClick={() => {
                        typeof props.onCancel === "function" && props.onCancel();
                    }}>取消</Button>
                </>}
            >
                    <section className={styles.fileManage}>
                        <Splitter style={{ height: '100%'}}>
                            <Splitter.Panel defaultSize="20%" min="20%" max="70%">
                                <Category />
                            </Splitter.Panel>
                            <Splitter.Panel>
                                <section className={styles.fileListWrapper}>
                                    <div className={styles.fileListToolbar}>
                                        <ToolBar />
                                    </div>
                                    <div className={styles.fileList}>
                                        <FileList
                                            onPlayVideo={onPlayVideo}
                                            defaultSelected={selectedList}
                                            multiple={props.mulitpleSelected}
                                            onChange={(newSelectedList, sourceList) => {
                                                setSelectedList(newSelectedList);
                                                setSelectedSourceList(sourceList);
                                                setHasChanged(true);
                                            }}
                                        />
                                    </div>
                                </section>
                            </Splitter.Panel>
                        </Splitter>
                        <div ref={playerRef} style={playerStyle} className={styles.videoContainer}>

                        </div>
                    </section>
            
            </Modal>
        </FileProvider>
    );
}

export default FileManage;
